/**
 * Created by Dave on 2017/3/10.
 */

var base = require('./mongodb');
var util = require('util');
var collection_name = require('../lib/config/config').config.mongodb.appConfigEnv_collection;
var jsonUtil = require('../lib/util/jsonUtil');
var logger = require('../lib/log4js/log4js').logger('appConfigEnvDB');
module.exports = appConfigEnv;
function appConfigEnv(){
    base.call(this,collection_name);
}
appConfigEnv.prototype.exists = function (db, queryData, cb) {
    this.getWithParam(null,queryData, cb);
}
appConfigEnv.prototype.addEnv=function(env){
    logger.debug("Start adding env.");
    return new Promise(function (resolve, reject) {
        logger.debug("Try to get history version of env");
        this.getWithParam(null, {
            namespace: env.namespace,
            name: env.name,
            serviceName: env.serviceName
        }, function (err, ret) {
            logger.debug("Callback from appConfigEnv base:"+err);
            if (err != null) {
                logger.debug("Error while getting env version:"+err);
                console.log(err);
                reject(err);
            }
            else {
                jsonUtil(ret);
                var maxVersion=new Number(ret.getMax(function(elem1,elem2){
                        return new Number(elem1.version)-new Number(elem2.version);
                    }).version)+new Number(1);
                if(maxVersion==null)
                    maxVersion=1;
                logger.debug("New version:"+maxVersion);
                resolve(""+maxVersion);
            }
        });
    }).then(function (val) {
        if(val==null){
            reject("error while querying data");
        }
        env.version=val;
        logger.debug("Try to insert env");
        return new Promise(function(resolve,reject){
            this.insert(null, env, function (err, ret) {
                if (err != null){
                    console.log(err);
                    reject(err);
                }
                else {
                    logger.debug("Inserted.");
                    resolve(ret);
                }
            });

        });
    });
}
util.inherits(appConfigEnv,base);
